//
//  LocalNetworkManager.swift
//  Library_y
//
//  Created by JC on 2023/6/6.
//

import Foundation
import Network

// 本地网络权限访问（“”想要查找并连接到本地网络上的设备）
@available(iOS 13.0, *)
final public class LocalNetworkManager: NSObject {
    
    static public let share = LocalNetworkManager()
    
    typealias AuthResult = (Bool) -> Void
    
    private var authResult: AuthResult?
    private var netService: NetService?
    private var browser: NWBrowser?
    
    // 授权申请
    internal func requestAuthorization(completion: AuthResult?) {
        authResult = completion
        guard #available(iOS 14, *) else {
            authResult?(true)
            return
        }
        iOS14_requestAuthorization()
    }
}

private var gBrowserKey: Void?
private var gNWConnectionKey: Void?

@available(iOS 14.0, *)
private
extension LocalNetworkManager {
    
    private func iOS14_requestAuthorization() {
        // Create parameters, and allow browsing over peer-to-peer link.
        let parameters = NWParameters()
        parameters.includePeerToPeer = true
        
        // Browse for a custom service type.
        let browser = NWBrowser(for: .bonjour(type: "_bonjour._tcp", domain: nil), using: parameters)
        self.browser = browser
        browser.stateUpdateHandler = { newState in
            switch newState {
            case .failed(let error):
                print(error.localizedDescription)
            case .ready, .cancelled:
                break
            case let .waiting(error):
                print("Local network permission has been denied: \(error)")
                self.reset()
                self.authResult?(false)
            default:
                break
            }
        }
        
        self.netService = NetService(domain: "local.", type:"_lnp._tcp.", name: "LocalNetworkPrivacy", port: 1100)
        self.netService?.delegate = self
        
        self.browser?.start(queue: .main)
        self.netService?.publish()
    }
    
    private func reset() {
        self.browser?.cancel()
        self.browser = nil
        self.netService?.stop()
        self.netService = nil
    }
}

@available(iOS 14.0, *)
extension LocalNetworkManager : NetServiceDelegate {
    public func netServiceDidPublish(_ sender: NetService) {
        Log_y.print_("Local network permission has been granted")
        self.reset()
        self.authResult?(true)
    }
}
